use tokio_postgres::Client;

pub const BLOG_TABLE_NAME: &str = "blogs";
pub const IDEA_TABLE_NAME: &str = "ideas";

async fn create_blog_table(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
    let sql = format!(
        "
CREATE TABLE IF NOT EXISTS {} (
    id SERIAL PRIMARY KEY,
    title VARCHAR(64) NOT NULL,
    content TEXT NOT NULL,
    tags VARCHAR(32)[],
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    author VARCHAR(64) NOT NULL,
    author_id VARCHAR(64) NOT NULL,
    FOREIGN KEY (author_id) REFERENCES users(id),
    views INTEGER DEFAULT 0,
    stars INTEGER DEFAULT 0
);",
        BLOG_TABLE_NAME
    );

    client.execute(&sql, &[]).await?;
    Ok(())
}

async fn create_idea_table(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
    let sql = format!(
        "
CREATE TABLE IF NOT EXISTS {} (
    id SERIAL PRIMARY KEY,
    title VARCHAR(64) NOT NULL,
    content TEXT NOT NULL,
    tags VARCHAR(32)[],
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    views INTEGER DEFAULT 0,
    stars INTEGER DEFAULT 0
);",
        IDEA_TABLE_NAME
    );

    client.execute(&sql, &[]).await?;
    Ok(())
}

pub async fn tables_init(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
    create_blog_table(client).await?;
    create_idea_table(client).await?;
    Ok(())
}
